//
//  LBImageColorMatrixFilter.mm
//  OpenGLGame
//
//  Created by Nguyen Cong Huy on 11/19/12.
//  Copyright (c) 2012 UIT. All rights reserved.
//

#include <iostream>
#include "LBImageColorMatrixFilter.h"
#include "LBGraphics.h"

char fShaderStrColorMatrixFilter[] = ""
"varying highp vec2 vtexCoor; "

"uniform sampler2D texture; "

"uniform lowp mat4 colorMatrix; "
"uniform lowp float intensity; "

"void main() "
"{ "
"    lowp vec4 textureColor = texture2D(texture, vtexCoor); "
"    lowp vec4 outputColor = textureColor * colorMatrix; "
    
"    gl_FragColor = (intensity * outputColor) + ((1.0 - intensity) * textureColor); "
"} ";

LBImageColorMatrixFilter::LBImageColorMatrixFilter(){
    init(0, fShaderStrColorMatrixFilter);
    
    intensityUniform = program->uniformIndex("intensity");
    colorMatrixUniform = program->uniformIndex("colorMatrix");
    
    setIntensity(1.0f);
    LBMatrix4x4 matrix = (LBMatrix4x4){
        {1.f, 0.f, 0.f, 0.f},
        {0.f, 1.f, 0.f, 0.f},
        {0.f, 0.f, 1.f, 0.f},
        {0.f, 0.f, 0.f, 1.f}
    };
    setColorMatrix(matrix);
}

LBImageColorMatrixFilter::LBImageColorMatrixFilter(float intensity, LBMatrix4x4 colorMatrix){
    init(0, fShaderStrColorMatrixFilter);
    
    intensityUniform = program->uniformIndex("intensity");
    colorMatrixUniform = program->uniformIndex("colorMatrix");
    
    setIntensity(intensity);
    setColorMatrix(colorMatrix);
}
void LBImageColorMatrixFilter::setIntensity(float intensity){
    this->intensity = intensity;
    LBGraphics::getInstance()->useProgram(program);
    glUniform1f(intensityUniform, intensity);
}
void LBImageColorMatrixFilter::setColorMatrix(LBMatrix4x4 colorMatrix){
    this->colorMatrix = colorMatrix;
    LBGraphics::getInstance()->useProgram(program);
    glUniformMatrix4fv(colorMatrixUniform, 1, GL_FALSE, (GLfloat*)&colorMatrix);
}